#include "systemconfigmanager.h"
#include <QStandardPaths>
#include <QCoreApplication>
#include <QDir>
#include <QDebug>
#include <QMutexLocker>
// 静态成员初始化
SystemConfigManager* SystemConfigManager::s_instance = nullptr;
QMutex SystemConfigManager::s_mutex;
SystemConfigManager& SystemConfigManager::instance()
{
    QMutexLocker locker(&s_mutex);
    if (!s_instance) {
        s_instance = createInstance();
    }
    return *s_instance;
}
void SystemConfigManager::destroyInstance()
{
    QMutexLocker locker(&s_mutex);
    if (s_instance) {
        delete s_instance;
        s_instance = nullptr;
    }
}
SystemConfigManager* SystemConfigManager::createInstance()
{
    return new SystemConfigManager();
}
SystemConfigManager::SystemConfigManager(QObject* parent)
    : QObject(parent)
    , m_settings(nullptr)
    , m_initialized(false)
{
    // 延迟创建QSettings实例，确保应用程序信息已设置
    // 连接应用程序退出信号
    connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit,
            this, &SystemConfigManager::onAboutToQuit);
}
SystemConfigManager::~SystemConfigManager()
{
    if (m_settings) {
        m_settings->endGroup();
    }
}
const SystemConfig& SystemConfigManager::getConfig() const
{
    QMutexLocker locker(&m_configMutex);
    if (!m_initialized) {
    }
    return m_config;
}
void SystemConfigManager::updateConfig(const SystemConfig& newConfig)
{
    QMutexLocker locker(&m_configMutex);
    // 检查配置是否有变化
    bool hasChanges = false;
    if (m_config.memoryStrategy != newConfig.memoryStrategy ||
        m_config.processingQuality != newConfig.processingQuality ||
        m_config.cacheDirectory != newConfig.cacheDirectory ||
        m_config.outputDirectory != newConfig.outputDirectory ||
        m_config.spaceThresholdGB != newConfig.spaceThresholdGB ||
        m_config.pdfDefaultLayout != newConfig.pdfDefaultLayout ||
        m_config.imageDefaultLayout != newConfig.imageDefaultLayout) {
        hasChanges = true;
    }
    if (!hasChanges) {
        return;
    }
    // 保存旧配置用于信号
    SystemConfig oldConfig = m_config;
    // 更新配置
    m_config = newConfig;
    m_initialized = true;
    // 立即保存配置
    saveConfigImpl();
    // 发出配置变更信号
    emit configChanged(oldConfig, m_config);
}
void SystemConfigManager::resetToDefaults()
{
    SystemConfig defaultConfig;
    updateConfig(defaultConfig);
}
void SystemConfigManager::saveConfig()
{
    QMutexLocker locker(&m_configMutex);
    saveConfigImpl();
}
void SystemConfigManager::reloadConfig()
{
    loadConfigImpl();
}
bool SystemConfigManager::isInitialized() const
{
    QMutexLocker locker(&m_configMutex);
    return m_initialized;
}
void SystemConfigManager::onAboutToQuit()
{
    saveConfig();
}
void SystemConfigManager::ensureSettingsInitialized() const
{
    if (!m_settings) {
        
        // 强制使用INI文件格式而不是注册表
        QString configPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
        QDir().mkpath(configPath);  // 确保目录存在
        QString iniPath = QDir(configPath).absoluteFilePath("system_config.ini");
        
        
        // 使用const_cast来修改mutable成员
        const_cast<SystemConfigManager*>(this)->m_settings = new QSettings(iniPath, QSettings::IniFormat, const_cast<SystemConfigManager*>(this));
        const_cast<SystemConfigManager*>(this)->m_settings->beginGroup("SystemConfig");
        
    }
}

void SystemConfigManager::loadConfigImpl()
{
    ensureSettingsInitialized();
    
    if (!m_settings) {
        return;
    }
    // 设置默认值
    m_config = SystemConfig();  // 使用构造函数的默认值
    // 从设置中读取值
    m_config.memoryStrategy = SystemConfig::memoryStrategyFromString(
        m_settings->value("memoryStrategy", "Balanced").toString());
    m_config.processingQuality = SystemConfig::processingQualityFromString(
        m_settings->value("processingQuality", "High").toString());
    m_config.cacheDirectory = m_settings->value("cacheDirectory",
        QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).toString();
    m_config.outputDirectory = m_settings->value("outputDirectory",
        QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)).toString();
    m_config.spaceThresholdGB = m_settings->value("spaceThresholdGB", 2).toInt();
    // 布局配置（如果存在）
    QString pdfLayoutStr = m_settings->value("pdfDefaultLayout", "SingleColumn").toString();
    QString imageLayoutStr = m_settings->value("imageDefaultLayout", "TwoColumns").toString();
    m_config.pdfDefaultLayout = SystemConfig::layoutModeFromString(pdfLayoutStr);
    m_config.imageDefaultLayout = SystemConfig::layoutModeFromString(imageLayoutStr);
    m_initialized = true;
}
void SystemConfigManager::saveConfigImpl()
{
    ensureSettingsInitialized();
    
    if (!m_settings || !m_initialized) {
        return;
    }
    
    
    // 保存所有配置项
    m_settings->setValue("memoryStrategy", SystemConfig::memoryStrategyToString(m_config.memoryStrategy));
    
    m_settings->setValue("processingQuality", SystemConfig::processingQualityToString(m_config.processingQuality));
    
    m_settings->setValue("cacheDirectory", m_config.cacheDirectory);
    
    m_settings->setValue("outputDirectory", m_config.outputDirectory);
    
    m_settings->setValue("spaceThresholdGB", m_config.spaceThresholdGB);
    
    m_settings->setValue("pdfDefaultLayout", SystemConfig::layoutModeToString(m_config.pdfDefaultLayout));
    
    m_settings->setValue("imageDefaultLayout", SystemConfig::layoutModeToString(m_config.imageDefaultLayout));
    
    // 确保立即写入磁盘
    m_settings->sync();
    
    // 验证文件
    QString filePath = m_settings->fileName();
    QFileInfo fileInfo(filePath);
    if (fileInfo.exists()) {
    } else {
    }
    
}
QSettings* SystemConfigManager::getSettings()
{
    return m_settings;
}

// === 窗口状态管理实现 ===

void SystemConfigManager::setWindowGeometry(const QByteArray& geometry)
{
    ensureSettingsInitialized();
    if (m_settings) {
        m_settings->setValue("windowGeometry", QString(geometry.toBase64()));
    }
}

QByteArray SystemConfigManager::getWindowGeometry() const
{
    ensureSettingsInitialized();
    if (m_settings) {
        QString geometryStr = m_settings->value("windowGeometry", "").toString();
        if (!geometryStr.isEmpty()) {
            QByteArray geometry = QByteArray::fromBase64(geometryStr.toUtf8());
            return geometry;
        }
    }
    return QByteArray();
}

void SystemConfigManager::setDockWidgetState(const QByteArray& state)
{
    ensureSettingsInitialized();
    if (m_settings) {
        m_settings->setValue("dockWidgetState", QString(state.toBase64()));
    }
}

QByteArray SystemConfigManager::getDockWidgetState() const
{
    ensureSettingsInitialized();
    if (m_settings) {
        QString stateStr = m_settings->value("dockWidgetState", "").toString();
        if (!stateStr.isEmpty()) {
            QByteArray state = QByteArray::fromBase64(stateStr.toUtf8());
            return state;
        }
    }
    return QByteArray();
}

void SystemConfigManager::setFileBrowserVisible(bool visible)
{
    ensureSettingsInitialized();
    if (m_settings) {
        m_settings->setValue("fileBrowserVisible", visible);
    }
}

bool SystemConfigManager::getFileBrowserVisible() const
{
    ensureSettingsInitialized();
    if (m_settings) {
        bool visible = m_settings->value("fileBrowserVisible", false).toBool();
        return visible;
    }
    return false;
}

void SystemConfigManager::setThumbnailVisible(bool visible)
{
    ensureSettingsInitialized();
    if (m_settings) {
        m_settings->setValue("thumbnailVisible", visible);
    }
}

bool SystemConfigManager::getThumbnailVisible() const
{
    ensureSettingsInitialized();
    if (m_settings) {
        bool visible = m_settings->value("thumbnailVisible", false).toBool();
        return visible;
    }
    return false;
}

void SystemConfigManager::setFileBrowserWidth(int width)
{
    ensureSettingsInitialized();
    if (m_settings) {
        m_settings->setValue("fileBrowserWidth", width);
    }
}

int SystemConfigManager::getFileBrowserWidth() const
{
    ensureSettingsInitialized();
    if (m_settings) {
        int width = m_settings->value("fileBrowserWidth", 300).toInt();
        return width;
    }
    return 300;
}

void SystemConfigManager::setThumbnailWidth(int width)
{
    ensureSettingsInitialized();
    if (m_settings) {
        m_settings->setValue("thumbnailWidth", width);
    }
}

int SystemConfigManager::getThumbnailWidth() const
{
    ensureSettingsInitialized();
    if (m_settings) {
        int width = m_settings->value("thumbnailWidth", 220).toInt();
        return width;
    }
    return 220;
}